/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Table, Notification } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import OperationChargeForm from './OperationChargeForm';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const BusPriceForm = ({ priceId, modal, onSubmit, onCancel }) => {
  const { busPriceStore: store } = useStore();
  const [operationCompany, setOperationCompany] = useState([]);
  const [idx, setIdx] = useState();
  const [operationCharge, setOperationCharge] = useState();
  const [companyModal, setCompanyModal] = useState({
    show: false,
    record: {},
  });
  const [companyData, setCompanyData] = useState({
    name: '',
    value: '',
  });
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [price] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const data = await store.get(priceId);
      // eslint-disable-next-line require-atomic-updates
      store.city = await store.getBusCity({ fromCity: '' });
      // eslint-disable-next-line require-atomic-updates
      store.fromStation = await store.getBusStation({
        fromCities: [data.startMainArea],
        toCities: [data.endMainArea],
        direction: '0',
        toStation: '',
        priceType: 3,
      });
      // eslint-disable-next-line require-atomic-updates
      store.toStation = await store.getBusStation({
        fromCities: [data.startMainArea],
        toCities: [data.endMainArea],
        direction: '1',
        toStation: '',
        priceType: 3,
      });
      if (priceId) {
        setOperationCompany(data?.operatingCompany);
        editCtx.origin = _.cloneDeep(data);
        _.assign(price, data);
      } else {
        // 添加操作,设置默认值
        _.set(price, 'priceType', '3');
        _.set(price, 'portTypes', ['0']);
        _.set(price, 'state', true);
      }
    })();
  }, []);

  if (!price) return <></>;

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
  };

  const operationColumns = [
    {
      title: t`运营公司`,
      dataIndex: 'companyName',
      width: 300,
      align: 'center',
    },
    {
      title: t`公司Id`,
      dataIndex: 'companyId',
      width: 200,
      align: 'center',
    },
    {
      title: t`是否启用`,
      dataIndex: 'enable',
      width: 200,
      align: 'center',
      cell: (v) => (v ? '启用' : '禁用'),
    },
    {
      title: t`操作`,
      align: 'center',
      width: 200,
      cell: (v, i) => (
        <>
          {/* <Button type="primary" text onClick={() => handleOperationCharge(r)}>{t`编辑`}</Button>
          <Divider direction="ver" /> */}
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteOperation(i)}>{t`删除`}</Button>
        </>
      ),
    },
  ];

  const handleAddOperation = () => {
    setCompanyModal({ show: true, record: {} });
  };

  const handleDeleteOperation = (i) => {
    setOperationCompany((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(price, name, value);
    if (name === 'startMainArea') {
      if (value === undefined) {
        store.fromStation = [];
        store.toStation = [];
        _.set(price, 'endMainArea', '');
        _.set(price, 'startMinorAreas', []);
        _.set(price, 'endMinorAreas', []);
      }
    }
    if (name === 'endMainArea') {
      if (value === undefined) {
        store.fromStation = [];
        store.toStation = [];
        _.set(price, 'startMinorAreas', []);
        _.set(price, 'endMinorAreas', []);
      }
      // eslint-disable-next-line require-atomic-updates
      store.fromStation = await store.getBusStation({
        fromCities: [price.startMainArea],
        toCities: [value],
        direction: '0',
        toStation: '',
        priceType: 3,
      });
      // eslint-disable-next-line require-atomic-updates
      store.toStation = await store.getBusStation({
        fromCities: [price.startMainArea],
        toCities: [value],
        direction: '1',
        toStation: '',
        priceType: 3,
      });
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const operationChargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setOperationCompany((pre) => {
      const newCharge = [...pre];
      newCharge[idx] = values;
      return newCharge;
    });
    setOperationCharge(false);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: BusPriceForm.jsx:188 _ errors:', errors);
      return;
    }
    if (operationCompany?.length === 0) {
      return Dialog.confirm({
        content: t`运营公司不能为空!`,
      });
    }
    price.operatingCompany = operationCompany;
    onSubmit?.(price);
  };

  const handleCompany = (e, __, r) => {
    setCompanyData({
      name: r.label,
      value: r.value,
    });
  };

  const handleCompanyOnOk = () => {
    const company = operationCompany;
    if (operationCompany.some((p) => p.companyId === companyData.value)) {
      Notification.warning({
        title: t`警告`,
        content: t`该公司已存在, 不可重复添加!`,
        duration: 3000,
      });
      return;
    }
    company.push({
      companyName: companyData.name,
      companyId: companyData.value,
      enable: true,
    });
    setOperationCompany(company);
    setCompanyModal({ show: false });
    setCompanyData({
      name: '',
      value: '',
    });
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={price}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['startMainArea', 'endMainArea']}
      />
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['startMinorAreas', 'endMinorAreas']}
      />
      <TitleGrid title={t`运营公司`} />
      <>
        <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddOperation()}>{t`添加运营公司`}</Button>
        <Table
          hasBorder={false}
          dataSource={operationCompany}
          columns={operationColumns}
          onRowClick={(__, index) => setIdx(index)}
        />
      </>
      <Dialog
        visible={!!operationCharge}
        onCancel={() => setOperationCharge(false)}
        onClose={() => setOperationCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <OperationChargeForm
          data={operationCharge}
          onSubmit={(r, errors) => operationChargeOnSubmit(r, errors)}
          onCancel={() => setOperationCharge(false)}
        />
      </Dialog>
      <Dialog
        visible={companyModal.show}
        title={t`选择公司`}
        onCancel={() => setCompanyModal({ show: false })}
        onClose={() => setCompanyModal({ show: false })}
        onOk={handleCompanyOnOk}
        style={{ width: 280 }}
      >
        <TauSimpleSelect style={{ width: '100%' }} dataSource={store.companySource} onChange={handleCompany} />
      </Dialog>
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(BusPriceForm);
